package org.rcy.framework.thrift.serializer;

import net.qiyuesuo.rpc.thrift.metadata.FieldValueMetaData;
import net.qiyuesuo.rpc.thrift.metadata.MapMetaData;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TMap;
import org.apache.thrift.protocol.TProtocol;

import java.util.HashMap;
import java.util.Map;


/**
 * Map序列化
 * @author zhouree
 */
public class MapSerializer implements Serializer {

	@Override
	public Object read(TProtocol iprot, FieldValueMetaData valueMetaData) throws TException {
		MapMetaData mapMetaData = (MapMetaData) valueMetaData;

		TMap tMap = iprot.readMapBegin();
		Map<Object,Object> success = new HashMap();
		for (int i = 0; i < tMap.size; i++) {
			Object key = ThriftSerializer.read(iprot, mapMetaData.keyMetaData);
			Object value = ThriftSerializer.read(iprot, mapMetaData.valueMetaData);
			success.put(key, value);
		}
		iprot.readMapEnd();
		return success;
	}

	@Override
	public void write(TProtocol oprot, FieldValueMetaData fieldValueMetaData, Object value) throws TException {
		MapMetaData mapMetaData = (MapMetaData) fieldValueMetaData;
		FieldValueMetaData keyMetaData = mapMetaData.keyMetaData;
		FieldValueMetaData valueMetaData = mapMetaData.valueMetaData;
		
		Map map = (Map) value;
		oprot.writeMapBegin(new TMap(keyMetaData.type,valueMetaData.type, map.size()));
		for (Object key : map.keySet()) {
			ThriftSerializer.write(oprot, keyMetaData, key);
			ThriftSerializer.write(oprot, valueMetaData, map.get(key));
		}
		oprot.writeMapEnd();
	}
}
